from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse, Http404
from django.core.files.uploadedfile import InMemoryUploadedFile
# from asset.models import DomainList
import whois
import nmap
from urllib import request as r
import os
import subprocess

headers = {
    'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3'
}

# whois查询
def who_is(request, action=None):
    if request.method == 'POST':
        target = request.POST.get('arg')
        print(target)
        res = whois.whois(target)
        l1 = []
        l2 = []
        for i, j in res.items():
            l1.append(i)
            l2.append(j)
        zip_data = zip(l1, l2)
        # result = request.GET.get('result')
        result = zip_data
        return render(request, 'info/who_is.html', {'result': result})

    else:
        return render(request, 'info/who_is.html')
        # return HttpResponse('fdgdg')
        # return render(request, 'info/port_scan.html')


# 端口扫描
def port_scan(request):
    if request.method == 'POST':
        target1 = request.POST.get('arg1')
        target2 = request.POST.get('arg2')
        target3 = request.POST.get('arg3')
        a = str(target1)
        b = str(target2)
        c = str(target3)
        print(a)
        print(b)
        print(c)

        nm = nmap.PortScanner()  # 导入函数
        # nm.scan(hosts='192.168.1.5', ports='1-500', arguments='-sS')

        nm.scan(hosts=a, ports=b, arguments=c)  # 输入你要扫描的ip与道口
        for host in nm.all_hosts():  # 返回被扫描的主机列表给host
            print('---------------------------------------------------------')
            print('Host : %s (%s)' % (host, nm[host].hostname()))  # nm[host].hostname()获取目标主机的主机名
            print('State : %s' % nm[host].state())  # nm[host].state()获取主机的状态  |up|down|unknow|skipped|
            all_protocal = nm[host].all_protocols()
            for proto in nm[host].all_protocols():  # nm[host].all_protocols获取执行的协议['tcp','udp']
                print('-----------------------------------------------------')
                print('protocol : %s' % proto)  # 输出执行的协议
                all_port = nm[host][proto].keys()  # 获取目标主机所开放的端口赋值给lport
                # lport.sort()
                l1=[]
                l2=[]
                for port in all_port:  # 将lport赋值给port并遍历
                    print('port : %s\tstate : %s' % (port, nm[host][proto][port]['state']))  # 输出扫描结果
                    l1.append([nm[host][proto][port]['state']])

                for i in l1:
                    for j in i:
                        l2.append(j)
                all_state=l2

                zipped_data = zip(all_port,all_state)
                print(l2)
                return render(request, 'info/port_scan.html', {'result': zipped_data})

    else:
        return render(request, 'info/port_scan.html')



# 主机存活检测
def hosts_scan(request, action=None):
    if request.method == 'POST':
        target1 = request.POST.get('arg1')
        target2 = request.POST.get('arg2')
        a = str(target1)
        b = str(target2)
        print('+++++++')
        print(a)
        print(b)
        print('+++++++')
        nm = nmap.PortScanner()  # 导入函数
        nm.scan(hosts=a, arguments=b)
        # nm.scan(hosts = '192.168.1.0/24',arguments = '-sP')  # 绑定网段与扫描模式
        hosts_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]  # 定义字典
        result = hosts_list
        return render(request, 'info/hosts_scan.html', {'result': result})
    else:
        return render(request, 'info/hosts_scan.html')
        return HttpResponse('aaaaaaaaaaaaaa')


#指纹识别
import requests
import zlib
import json
from asset import cms
def web_ident(request, action=None):
    # def whatweb(url):
    #     response = requests.get(url, verify=False)
    #     # 上面的代码可以随意发挥,只要获取到response即可
    #     # 下面的代码您无需改变，直接使用即可
    #     whatweb_dict = {"url": response.url, "text": response.text, "headers": dict(response.headers)}
    #     whatweb_dict = json.dumps(whatweb_dict)
    #     whatweb_dict = whatweb_dict.encode()
    #     whatweb_dict = zlib.compress(whatweb_dict)
    #     data = {"info": whatweb_dict}
    #     return requests.post("http://whatweb.bugscaner.com/api.go", files=data)
    if request.method == 'POST':
        target = request.POST.get('arg')
        ret = cms.whatweb(target)
        print(ret)
        return render(request, 'info/web_identqqqq.html', {'result': ret})
    else:
        # ret = cms.whatweb('http://www.jnbec.com/')
        # print(ret)
        return render(request, 'info/web_identqqqq.html')
        # return HttpResponse(ret)


# 旁站扫描
from asset import otherdomain
def domain_scan(request, action=None):
    if request.method == 'POST':
        target = request.POST.get('arg')
        ip = otherdomain.getip(target)
        info = otherdomain.run(ip)
        l1=[]
        l2=[]
        zip_data = zip(l1,l2)
        for i in info:
            l1.append(i['title'])
            l2.append(i['domain'])
            zip_data=zip(l1,l2)
        # cduan = otherdomain.cduan(ip)
        return render(request, 'info/domain_scan.html', {'result1': ip,'result2':zip_data})


    else:
        return render(request, 'info/domain_scan.html')
